package repositories

import (
	"errors"
	"fox/db"
	"fox/models"
	request2 "fox/request"
	response2 "fox/response"
	"gorm.io/gorm"
	"math"
)

type RoleRepository struct {
}

func NewRoleRepository() (roleRepository *RoleRepository) {
	return &RoleRepository{}
}

// InsertRole 添加角色
func (repository *RoleRepository) InsertRole(role *models.Role) (id int64, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Create(role)
	if result.RowsAffected == 1 {
		return role.ID, err
	}
	return 0, result.Error
}

// DeleteRoleById 删除角色
func (repository *RoleRepository) DeleteRoleById(id int64) (err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Delete(&models.Role{ID: id})
	if result.RowsAffected == 1 && result.Error == nil {
		return err
	}
	return result.Error
}

// UpdateRoleById 修改角色信息
func (repository *RoleRepository) UpdateRoleById(role *models.Role) (newRole *models.Role, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Model(&models.Role{ID: role.ID}).UpdateColumns(role)
	result.Scan(&newRole)
	return newRole, result.Error

}

// SelectRoleById 查找角色信息
func (repository *RoleRepository) SelectRoleById(id int64) (role *models.Role, err error) {
	var (
		result *gorm.DB
	)

	result = db.GDatabase.Db.Where("id = ?", id).First(&role)
	if result.RowsAffected == 1 {
		return role, nil
	}
	if result.RowsAffected == 0 {
		return nil, errors.New("没有查找到记录")
	}
	return role, result.Error
}

// SelectRoles 分页获取角色信息
func (repository *RoleRepository) SelectRoles(role *request2.Role) (result *response2.Result, err error) {
	var (
		offset    int
		roles     *[]models.Role
		countRole *models.Role
		count     int64
		totalPage int
	)
	countRole = new(models.Role)
	countRole.Name = role.Name
	count = repository.CountRoles(countRole)
	if count == 0 {
		result.Total = 0
		result.Size = role.Size
		result.Page = role.Page
		result.Lists = make([]interface{}, 0)
		return result, err
	}

	totalPage = int(math.Ceil(float64(count) / float64(role.Size)))
	offset = (role.Page - 1) * role.Size
	db.GDatabase.Db.Scopes(request2.Paginate(offset, role.Size), repository.filterRoleName(role.Name)).Model(&models.Role{}).Order(role.SortField + " " + role.Sort).Find(&roles)
	return &response2.Result{
		Total:     count,
		TotalPage: totalPage,
		Page:      role.Page,
		Size:      role.Size,
		Lists:     roles,
	}, err
}

// CountRoles 统计分页数
func (repository *RoleRepository) CountRoles(role *models.Role) (count int64) {

	db.GDatabase.Db.Scopes(repository.filterRoleName(role.Name)).Model(&models.Role{}).Count(&count)
	return count
}

// 增加where查询
func (repository *RoleRepository) filterRoleName(name string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if name != "" {
			return db.Where("name LIKE ?", "%"+name+"%")
		}
		return db
	}
}
